package com.zretc.question.service;

import com.zretc.answer.dao.AnswerMapper;
import com.zretc.api.pojo.Answer;
import com.zretc.api.pojo.Question;
import com.zretc.question.dao.QuestionMapper;
import com.zretc.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Transactional
public class QuestionService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private AnswerMapper answerMapper;
    public boolean giveQuestion(Question question)
    {
        return questionMapper.addSingleRecord(question)==1;
    }
    public boolean deleteQuestionByUser(Integer id,Integer createdBy)
    {
        //删除问题和其附带的回答
        //如果传来的创建人确实是问题的创建人，并且附带的问题是有答案的则删除两个表的相关记录
        if(createdBy==questionMapper.getCreatedByOfQuestionById(id)&&questionMapper.getAnswerCountsOfQuestion(id)!=0)
        {
            return questionMapper.deleteSingleRecord(id)==1&&answerMapper.deleteRecordsByQuestionId(id)!=0;
        }
        //否则就删除其中一个表就够了
        return questionMapper.deleteSingleRecord(id)==1;
    }
    public boolean deleteQuestionByIRPublisher(Integer id,Integer iRPublisherId )
    {
        if(iRPublisherId==questionMapper.getIRPublisherIdOfQuestionById(id)&&questionMapper.getAnswerCountsOfQuestion(id)!=0)
        {
            return questionMapper.deleteSingleRecord(id)==1&&answerMapper.deleteRecordsByQuestionId(id)!=0;
        }
        return questionMapper.deleteSingleRecord(id)==1;
    }
    public List<Question> queryQuestionsByAmountByIRId(Integer index,Integer pageNum,Integer iRId)
    {
        String redisKey="IR:"+iRId+"questionList:"+index+","+pageNum;
        List<Question> result=redisService.getCacheList(redisKey);
        if (CollectionUtils.isEmpty(result))
        {
            result=questionMapper.getQuestionsByAmountByIRId(index, pageNum, iRId);
            if (CollectionUtils.isEmpty(result))return null;
            redisService.setCacheList(redisKey,result);
        }
        redisService.expire(redisKey,5);
        return result;
    }
}
